{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b101b872",
   "metadata": {},
   "outputs": [],
   "source": [
    "import findspark\n",
    "findspark.init()\n",
    "from pyspark import SparkContext, SparkConf\n",
    "conf = SparkConf()\n",
    "sc = SparkContext(conf=conf)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b3d4237",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 练习题7 计算每个学生分数最高的3个成绩 \n",
    "# Andy,99\n",
    "# Mike,88\n",
    "# Bill,99\n",
    "# Bill,88,\n",
    "# Andy,87\n",
    "rdd = sc.textFile(\"file:///C:/Users/Administrator/Desktop/demo/score.txt\")\n",
    "rdd1 = rdd \\\n",
    "    .map(lambda x: x.split(\",\")) \\\n",
    "    .map(lambda x: (x[0],x[1])) \\\n",
    "    .groupByKey() \\\n",
    "    .map(lambda x: (x[0], list(x[1]))) \\\n",
    "    .mapValues(lambda x: sorted(x, reverse=True)) \\\n",
    "    .mapValues(lambda x: x[:3])\n",
    "\n",
    "print(rdd1.collect())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ff7d7d19",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 练习题8 计算每日用户新增数量\n",
    "# 2022-10-01 user1\n",
    "# 2022-10-01 user2\n",
    "# 2022-10-01 user3\n",
    "# 2022-10-02 user1\n",
    "# 2022-10-02 user2\n",
    "# 2022-10-02 user4\n",
    "# 2022-10-03 user2\n",
    "# 2022-10-03 user5\n",
    "# 2022-10-03 user6\n",
    "rdd = sc.textFile(\"file:///C:/Users/Administrator/Desktop/demo/users.txt\")\n",
    "rdd1 = rdd \\\n",
    "    .map(lambda x: x.split(\" \")) \\\n",
    "    .map(lambda x: (x[1],x[0])) \\\n",
    "    .groupByKey() \\\n",
    "    .map(lambda x: (x[0], min(x[1]))) \\\n",
    "    .map(lambda x: (x[1], x[0])) \\\n",
    "    .groupByKey() \\\n",
    "    .map(lambda x: (x[0], list(x[1])))\n",
    "\n",
    "print(rdd1.collect())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.12 ('base')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  },
  "vscode": {
   "interpreter": {
    "hash": "e42634819b8c191a5d07eaf23810ff32516dd8d3875f28ec3e488928fbd3c187"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
